/**
 * 
 */
package co.fitstart.api.web.controller.trading;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.api.handler.PaymentHandler;
import co.fitstart.api.service.OrderService;
import co.fitstart.entity.order.PaymentRequest;

/**
 * @author downpour
 *
 */
@Controller
@RequestMapping("/v1/payments")
public class PaymentController {
    
    private static Logger logger = LoggerFactory.getLogger(PaymentController.class);
    
    @Autowired
    private PaymentHandler paymentHandler;
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 
     * @param body
     * @param request
     * @return
     */
    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    public @ResponseBody String onPyamentCallback(@RequestBody String body,
                                                  HttpServletRequest request) {
        
        PaymentRequest paymentRequest = JSON.parseObject(body, PaymentRequest.class);
        
        logger.trace("PaymentController#onSyncOrder - Get rquest number [{}], order number [{}], amount [{}], pay time [{}], channel [{}].", 
                     paymentRequest.getRequestNo(), paymentRequest.getOrderNo(), paymentRequest.getAmount(), paymentRequest.getPayTime(), paymentRequest.getChannel());
                                
        Result result = new Result();
        
        try {
            
            // check paymentRequest & signature
            paymentHandler.check(paymentRequest);
            
            // check order & update order, product things
            result = orderService.callback(paymentRequest);
            
            logger.trace("PaymentController#onSyncOrder() - Synchronizing order with result [{}] !!!!!!!!", result.getMessage());
            
        } catch (BusinessException e) {
            
            logger.error("PaymentController#onSyncOrder() - Synchronizing order encounters exception: {}", e);
            result.fail("500").message(e.getMessage());
            return JsonUtils.toJsonString(result);
            
        } catch (Exception e) {
            logger.error("PaymentController#onSyncOrder() - Synchronizing order encounters exception: {}", e);
            result.fail("500").message(e.getMessage());
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
//    /**
//     * 
//     * @param appid
//     * @param requestNo
//     * @param orderNo
//     * @param customerId
//     * @param amount
//     * @param payTimeString
//     * @param channel
//     * @param signature
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/callback", method = RequestMethod.POST)
//    public @ResponseBody String onPyamentCallback(@RequestParam("appid") String appid,
//                                                  @RequestParam("request_no") String requestNo,
//                                                  @RequestParam("order_no") String orderNo,
//                                                  @RequestParam("customer_id") Long customerId,
//                                                  @RequestParam("amount") int amount,
//                                                  @RequestParam("pay_time") String payTimeString,
//                                                  @RequestParam("channel") String channel,
//                                                  @RequestParam("signature") String signature,
//                                                  HttpServletRequest request) {
//        
//        logger.trace("PaymentController#onSyncOrder - Get rquest number [{}], order number [{}], customer id [{}], amount [{}], pay time [{}], channel [{}] and singature [{}].", requestNo, orderNo, customerId, amount, payTimeString, channel, signature);
//                                
//        Result result = new Result();
//                                
//        boolean isValid = paymentHandler.checkSignature(request);
//        
//        if (!isValid) {
//            logger.error("PaymentController#onSyncOrder() - Check oreder sync request signature fails...");
//            return JsonUtils.toJsonString(result.fail().message("签名校验失败"));
//        }
//        
//        logger.trace("PaymentController#onSyncOrder - Signature validation passes...");
//        
//        // 1. Get order according to order number
//        Order order = orderService.getOrder(orderNo);
//        if (order == null) {
//            logger.error("PaymentController#onSyncOrder() - Can not find order with order no [{}].", orderNo);
//            return JsonUtils.toJsonString(result.fail().message("订单" + orderNo + "不存在"));
//        }
//        
//        // 2. Check order matches customer
//        if (!order.matches(customerId)) {
//            logger.error("PaymentController#onSyncOrder() - Order customer id [{}] is not equals to customer id [{}].", order.getUser().getId(), customerId);
//            return JsonUtils.toJsonString(result.fail().message("订单用户不匹配"));
//        }
//        
//        // 3. Only sync order when order is unpaid
//        if (order.isUnpaid()) {
//            Date payTime = DateUtils.parseDate(payTimeString, "yyyyMMddHHmmss");
//            PaymentMethod paymentMethod = PaymentMethod.aliasOf(channel.split("_")[0]); 
//            try {
//                
//                // do sync order
//                orderService.callback(order, requestNo, amount, payTime, paymentMethod);
//                result.success().message("订单同步成功");
//                
//            } catch (Exception e) {
//                logger.error("PaymentController#onSyncOrder() - Synchronizing order encounters exception: {}", e);
//                result.fail().message(e.getMessage());
//            }
//        } else {
//            logger.trace("PaymentController#onSyncOrder() - Order has been sychronized. So we do nothing but return success.");
//        }
//        
//        return JsonUtils.toJsonString(result);
//    }

}
